﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.Text;
using System.Threading.Tasks;
using StyleMVVM.DependencyInjection;

namespace StyleMVVM.WCF.LanguageExtensions
{
	public class OperationCustomDataExtension : IExtension<OperationContext>, IDisposable
	{
		private DisposalScope disposalScope = new DisposalScope();

		public OperationCustomDataExtension()
		{
			Items = new Dictionary<object, object>();
		}

		public IDictionary<object, object> Items { get; private set; }

		public IDisposalScope DisposalScope
		{
			get { return disposalScope; }
		}

		public void Attach(OperationContext owner)
		{
		}

		public void Detach(OperationContext owner)
		{
		}

		public void Dispose()
		{
			Dispose(true);
		}

		private void Dispose(bool dispose)
		{
			if (dispose && disposalScope != null)
			{
				disposalScope.Dispose();

				disposalScope = null;

				GC.SuppressFinalize(this);
			}
		}
	}

	public static class OperationContextExtensions
	{
		public static IDictionary<object, object> Items(this OperationContext operationContext)
		{
			return GetExtension(operationContext).Items;
		}

		public static IDisposalScope DisposalScope(this OperationContext operationContext)
		{
			return GetExtension(operationContext).DisposalScope;
		}

		private static OperationCustomDataExtension GetExtension(OperationContext operationContext)
		{
			OperationCustomDataExtension extension = operationContext.Extensions.Find<OperationCustomDataExtension>();

			if (extension == null)
			{
				extension = new OperationCustomDataExtension();

				operationContext.Extensions.Add(extension);
			}

			return extension;
		}
	}
}